package com.banggood.upms.common.util;

import com.banggood.upms.bean.vo.UpmsCredentials;
import com.banggood.upms.common.constant.UpmsConstant;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.StringTokenizer;

/**
 * 提取Authorization请求头里面的账号密码
 * @author XuChuangFeng
 * @date 2017/11/8
 */
public class BasicAuthorizationUtil {

    public final static String COLON = ":";

    public final static String AUTHORIZATION = "Authorization";

    public final static String REQUEST_IP = "lastLoginIp";

    public final static String USER_AGENT = "User-Agent";

    public static String extractToken(String basicAuthorization) {
        StringTokenizer basicToken = new StringTokenizer(basicAuthorization);
        if(UpmsConstant.AUTHORIZATION_BASIC.equals(basicToken.nextToken()) && basicToken.hasMoreTokens()) {
            return basicToken.nextToken();
        }
        return null;
    }

    public static UpmsCredentials parseToken(String credential) {
        if(StringUtils.isEmpty(credential)) {
            return null;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(credential);
        String credentialStr = new String(decode);
        if(!credentialStr.contains(COLON)) {
            return null;
        }
        String[] userNameAndPwd = credentialStr.split(COLON);
        UpmsCredentials upmsCredentials = new UpmsCredentials();
        upmsCredentials.setAccount(userNameAndPwd[0]);
        upmsCredentials.setPassword(userNameAndPwd[1]);
        return upmsCredentials;
    }

    public static UpmsCredentials parseCredentialsFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader(AUTHORIZATION);
//        String lastLoginIp = request.getHeader(REQUEST_IP);
        String requestIp = request.getRemoteHost();
        UpmsCredentials upmsCredentials = BasicAuthorizationUtil.parseToken(BasicAuthorizationUtil.extractToken(authorization));
        if(upmsCredentials == null) {
            return null;
        }
        upmsCredentials.setLastLoginIp(requestIp);
        upmsCredentials.setLastUserAgent(request.getHeader(USER_AGENT));
        upmsCredentials.setLastLoginDate(TimeUtils.getCurrentTimeStr());
        return upmsCredentials;
    }
}
